<?php

namespace App\Exceptions;

use Exception;
use App\Traits\Response\InterfaceResponse;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class Handler extends ExceptionHandler
{
    use InterfaceResponse;
    /**
     * A list of the exception types that are not reported.
     * 定义不需要记录的异常类
     *
     * @var array
     */
    protected $dontReport = [
        //
        HttpException::class,
        ValidationException::class,
        ModelNotFoundException::class,
        AuthorizationException::class,
        AuthenticationException::class
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        //拦截普通错误并产生响应
        if ( $exception instanceof OrdinaryException ) {
            return $this->failed($exception->getMessage(), $exception->getCode()?:500);
        }
        //拦截404异常
        if ( $exception instanceof ModelNotFoundException ) {
             return $this->notFound();
        }
        //拦截授权异常
        if ( $exception instanceof AuthenticationException ) {
            return $this->failed("您无权访问", 403);
        }
        //拦截参数验证错误异常
        if ( $exception instanceof ValidationException ) {
            return $this->failed( array_first(array_collapse($exception->errors())), 422 );
        }
        //拦截用户认证异常
        if ( $exception instanceof UnauthorizedHttpException ) {
            return $this->failed("未提供TOKEN", 401);
        }

        return parent::render($request, $exception);
    }
}
